import { Text, View, StyleSheet, Button, Pressable, TextInput, TouchableOpacity, Dimensions } from 'react-native';
import React, { useState, useRef, useEffect } from 'react';
import { Input, Icon, PresenceTransition, DeleteIcon } from 'native-base';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { useReactive } from 'ahooks';
import { CommonStyle } from '../common/commonStyle';
import { EOrderState, EOrderTimes } from '../common/enum';
import DatePicker from '../component/DatePicker';

interface ISearchScreenProps {
  onConfirm: (params: IScreen) => void;
  onRepeat: (params: IScreen) => void;
}

interface IScreen {
  orderState: number| string;
  date: number | string;
  beginDate: string;
  endDate: string;
  groupValue: string;
}

interface IData {
  screenShow: boolean;
  orderState: number;
  date: number;
  beginDate: string;
  endDate: string;
  year: number;
  month: string | number;
  dates: string | number;
  timeSelect: number;
  groupValue: string;
}

const wHeight = Dimensions.get('window').height;

const SearchScreen: React.FC<ISearchScreenProps> = ({ onConfirm, onRepeat }) => {
  const data = useReactive<IData>({
    screenShow: false,
    date: 0,
    orderState: 0,
    beginDate: '',
    endDate: '',
    groupValue: '',
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    dates: new Date().getDate(),
    timeSelect: 1,
  });
  const [isModalVisible, setModalVisible] = useState(false);
  const [screenH, setScreenH] = useState(0);
  const viewLayout = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    setScreenH(height);
  };
  const getDateStr = (year: number, month: string, date: string): string => {
    return `${year}-${month}-${date}`;
  };

  const stateArr = Object.keys(EOrderState)
    .filter((key) => !isNaN(Number(EOrderState[key as keyof typeof EOrderState])))
    .map((key) => ({
      id: EOrderState[key as keyof typeof EOrderState],
      name: key,
    }));

  const timeArr = Object.keys(EOrderTimes)
    .filter((key) => !isNaN(Number(EOrderTimes[key as keyof typeof EOrderTimes])))
    .map((key) => ({
      id: EOrderTimes[key as keyof typeof EOrderTimes],
      name: key,
    }));

  const repeatChange = () => {
    data.beginDate = '';
    data.endDate = '';
    data.orderState = 0;
    data.date = 0;
    data.groupValue = ""
    onRepeat({
      beginDate: data.beginDate,
      endDate: data.endDate,
      orderState: data.orderState,
      date: data.date,
      groupValue: data.groupValue,
    });
    data.screenShow = false;
  };
  const cofirmChange = () => {
    let params = {
        beginDate: data.beginDate,
        endDate: data.endDate,
        orderState: data.orderState===0?'':data.orderState,
        date: data.date===0?'':data.date,
        groupValue: data.groupValue,
    }
    onConfirm(params);
    data.screenShow = false;
  };

  return (
    <View>
      <View
        style={styles.flexView}
        onLayout={(e) => {
          viewLayout(e);
        }}
      >
        <View style={styles.flexLeft}>
          <Input
            backgroundColor={'#fff'}
            w={'100%'}
            pl={2}
            h={10}
            InputLeftElement={<Icon as={<AntDesign style={{ marginLeft: 10 }} name="search1" size={16}></AntDesign>} />}
            variant="rounded"
            placeholder="请输入订单编号、商品名"
            value={data.groupValue}
            onChangeText={(e) => {
              data.groupValue = e;
            }}
          />
        </View>
        <TouchableOpacity
          style={styles.flexRight}
          onPress={() => {
            data.screenShow = !data.screenShow;
          }}
        >
          <AntDesign name="bars" style={{ textAlign: 'center', marginRight: 4 }} color={'#fff'} size={16}></AntDesign>
          <Text style={{ color: '#fff', fontSize: 16 }}>筛选</Text>
        </TouchableOpacity>
      </View>
      {data.screenShow && (
        <View style={[styles.screenBox, { height: wHeight - screenH }]}>
          <View style={styles.screenZzc}></View>
          <View style={styles.screenContainer}>
            <View style={styles.state}>
              {stateArr.map((item, index) => (
                <TouchableOpacity
                  onPress={() => {
                    data.orderState = item.id;
                  }}
                  style={[styles.stateItem, data.orderState === item.id && styles.selectItem]}
                >
                  <Text style={{ color: '#000' }}>{item.name}</Text>
                </TouchableOpacity>
              ))}
            </View>
            <View style={styles.title}>
              <Text style={{ color: '#000' }}>筛选时间</Text>
            </View>
            <View style={styles.time}>
              {timeArr.map((item, index) => (
                <TouchableOpacity
                  onPress={() => {
                    data.date = item.id;
                    data.beginDate = ''
                    data.endDate = ''
                  }}
                  style={[styles.timeItem, data.date === item.id && styles.selectItem]}
                >
                  <Text style={{ color: '#000' }}>{item.name}</Text>
                </TouchableOpacity>
              ))}
            </View>
            <View style={styles.timeRange}>
              <TouchableOpacity
                style={styles.timeRitem}
                onPress={() => {
                  setModalVisible(true);
                  data.timeSelect = 1;
                }}
              >
                <Text style={{ color: '#000' }}>{data.beginDate ? data.beginDate : '起始时间'}</Text>
              </TouchableOpacity>
              <View style={{ flex: 1, alignItems: 'center' }}>
                <Text style={{ color: '#000' }}>至</Text>
              </View>
              <TouchableOpacity
                style={styles.timeRitem}
                onPress={() => {
                  setModalVisible(true);
                  data.timeSelect = 2;
                }}
              >
                <Text style={{ color: '#000' }}>{data.endDate ? data.endDate : '结束时间'}</Text>
              </TouchableOpacity>
            </View>
            <View style={styles.screenBtn}>
              <TouchableOpacity style={styles.screenRepeat} onPress={repeatChange}>
                <Text style={{ color: '#000' }}>重置</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.screenConfirm} onPress={cofirmChange}>
                <Text style={{ color: '#fff' }}>确定</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      )}
      <DatePicker
        show={isModalVisible}
        currentDate={[data.year, data.month, data.dates]}
        columnsType={['year', 'month', 'day']}
        minDate={`2019,01,01`}
        maxDate={`${new Date().getFullYear()},${new Date().getMonth() + 1},${new Date().getDate() + 1}`}
        closeOnClickOverlay
        onClose={() => setModalVisible(false)}
        onConfirm={(date) => {
          data.year = Number(date[0]);
          data.month = date[1];
          data.dates = date[2];
          if (data.timeSelect === 1) {
            data.beginDate = getDateStr(data.year, data.month, data.dates);
          } else {
            data.endDate = getDateStr(data.year, data.month, data.dates);
          }
          data.date = 0
          setModalVisible(false);
        }}
        title={'选择时间'}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  flexView: {
    flexDirection: 'row',
    backgroundColor: CommonStyle.mainColor,
    paddingVertical: 10,
    paddingHorizontal: 10,
    alignItems: 'center',
  },
  flexLeft: {
    width: '80%',
  },
  flexRight: {
    width: '20%',
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  screenBox: {
    width: '100%',
    position: 'relative',
  },
  screenZzc: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: '100%',
    height: '100%',
    backgroundColor: '#000',
    opacity: 0.6,
    zIndex: 1,
  },
  screenContainer: {
    position: 'absolute',
    width: '100%',
    height: 'auto',
    backgroundColor: '#eee',
    paddingBottom: 6,
    zIndex: 4,
  },
  screenBtn: {
    flexDirection: 'row',
    padding: 10,
    justifyContent: 'space-between',
  },
  screenRepeat: {
    width: '45%',
    height: 36,
    alignItems: 'center',
    backgroundColor: '#fff',
    paddingVertical: 6,
    borderRadius: 8,
  },
  screenConfirm: {
    width: '45%',
    alignItems: 'center',
    backgroundColor: CommonStyle.mainColor,
    paddingVertical: 6,
    borderRadius: 8,
    height: 36,
  },
  title: {
    paddingHorizontal: 10,
  },
  state: {
    padding: 10,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  stateItem: {
    width: '30%',
    justifyContent: 'center',
    alignItems: 'center',
    height: 34,
    backgroundColor: '#fff',
    marginBottom: 10,
    borderRadius: 8,
  },
  time: {
    padding: 10,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  timeItem: {
    width: '30%',
    justifyContent: 'center',
    alignItems: 'center',
    height: 34,
    backgroundColor: '#fff',
    marginBottom: 10,
    borderRadius: 8,
  },
  timeRange: {
    padding: 10,
    flexDirection: 'row',
    alignItems: 'center',
  },
  timeRitem: {
    flex: 2,
    backgroundColor: '#fff',
    height: 34,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selectItem: {
    borderWidth: 1,
    borderColor: CommonStyle.mainColor,
    backgroundColor: '#d5efd7',
  },
});

export default SearchScreen;
